#include <iostream>
#include <string>
#include <unistd.h>
#include <fstream>
#define DEBUG 1 


//打印指定文件的所有内容// 测试用
void printFileContent(const std::string& filename) 
{
    std::ifstream file(filename);
    if (file.is_open()) 
    {
        std::string line;
        while (getline(file, line)) 
        {
            std::cerr << line << std::endl;
        }
        file.close();

        std::cerr << "printFileContent over normal" << std::endl ; 
    } 
    else 
    {
        std::cerr << "Unable to open file: " << filename << std::endl;
    }
}



// POST请求则提取正文
// GET请求则提取未分割的参数
bool getCgiQueryString(std::string& query_string)
{
    bool result = false ; 
    std::string query_method = getenv("METHOD") ;

#ifdef DEBUG
    std::cerr << query_method << std::endl; 
    if(query_method == "")
    {
        std::cerr << "get env error" << std::endl ;
    }
#endif 

    if(query_method == "POST")
    {
        int content_length = atoi(getenv("CONTENT_LENGTH"));
        char tem  =  0 ; 
        while(content_length)
        {
            read(0, &tem, 1);
            query_string.push_back(tem); 
            content_length-- ; 
        }
        result = true ; 

    }
    else if (query_method == "GET")
    {
        query_string =  getenv("QUERY_STRING");
        result = true ; 
    }
    else
    {
        result = false ;
    }

    return result ;
}


    bool cutString(const std::string &target, std::string& out1, std::string& out2, std::string sep)
    {
#ifdef DEBUG
    std::cerr << "debug :" << target << std::endl ; 
    if(target == "")
    {
        std::cerr << "cutString env error"  << std::endl;
    }
#endif 


        int pos = target.find(sep);
        if(pos != std::string::npos)
        {
            out1 = target.substr(0, pos);
            out2 = target.substr(pos + sep.size()) ;
            return true ;
        }
        return false ; 
    }


// 处理带参GET方法(参数个数为2个)的
bool getAcountNumberAndPassword(std::string& account, std::string& password)
{
    std::string query_string ; 
    
    if(getCgiQueryString(query_string) == true)
    {
    
    std::string str1 ;
    std::string str2 ; 
    cutString(query_string, str1, str2, "&");

    std::string name1;
    std::string value1;
    cutString(str1, name1, value1, "=");

    std::string name2;
    std::string value2;
    cutString(str2, name2, value2, "=");

    account = value1 ; 
    password = value2 ; 

    return true ; 

    }
    else
    {

    return false ; 

    }
}



